<?php

namespace App\Models;

use App\Admin\Helper;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\HigherOrderCollectionProxy;
use hg\apidoc\annotation as Apidoc;

/**
 * App\Models\Worker
 *
 * @property int $id
 * @property int $shop_id 店铺ID
 * @property int $user_id 用户ID
 * @property string|null $image 图片
 * @property string $name 名称
 * @property string $phone 电话
 * @property string $money 可提现余额
 * @property string $used_money 已提现余额
 * @property float wait_money 待结算金额
 * @property int $province_id 省ID
 * @property int $city_id 市ID
 * @property int $district_id 区ID
 * @property string $area 所在区域
 * @property int $status 状态:0=正常,1=隐藏
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|Worker newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Worker newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|Worker query()
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereImage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker wherePhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereShopId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereUsedMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereUserId($value)
 * @mixin \Eloquent
 * @property-read \App\Models\ShopUser|null $shop
 * @property-read \App\Models\User|null $user
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereArea($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereCityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereDistrictId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|Worker whereProvinceId($value)
 */
class Worker extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'worker';

    protected static function booted()
    {
       self::saving(function (Worker $row){
           if ($row->isDirty("district_id")){
               list($province_id, $city_id) = Helper::findFromDistrictId($row->district_id);
               $row->province_id = $province_id;
               $row->city_id = $city_id;
               $area = Area::query()->whereIn("id",[$province_id,$city_id,$row->district_id])->pluck("name")->toArray();
               if ($area){
                   $row->area = implode("",$area);
               }
           }
       });
    }

    /**
     * @param $worker_id
     */
    public static function findShopId($worker_id){
        $worker = self::find($worker_id);
        if (!$worker){
            throw new Exception("暂无此门店师傅信息!");
        }
        return $worker->shop_id;
    }

    /**
     * @param $worker_id
     * @return HigherOrderCollectionProxy|int|mixed
     */
    public static function findUserId($worker_id): mixed
    {
        $worker = self::find($worker_id);
        return $worker->user_id??0;
    }

    /**
     * @param $user_id
     * @return HigherOrderCollectionProxy|int|mixed
     */
    public static function findId($user_id): mixed
    {
        $worker = self::query()->where("user_id",$user_id)->first();
        return $worker->id??0;
    }

    public function user(){
        return $this->hasOne(User::class,"id","user_id");
    }

    public function shop(){
        return $this->hasOne(ShopUser::class,"id","shop_id");
    }

    public static function getList(): array
    {
        $shop_id = request()->input("shop_id",0);
        $list = self::query()
            ->where("shop_id",$shop_id)
            ->where("status",0)
            ->orderByDesc("id")
            ->get();
        foreach ($list as $key=>$item){
            $list[$key] = Helper::workers($item);
        }
        return [
            'items'=> $list,
        ];
    }

    public static function getShops(): array
    {
        $shop_id = request()->input('shop_id',0);
//        $longitude = request()->input('longitude',113.348717);
//        $longitude = $longitude?:113.348717;
//        $latitude = request()->input('latitude',23.02165);
//        $latitude = $latitude?:23.02165;
//        $distance = ShopUser::getDistanceField($longitude,$latitude);
//        $limit = request()->input("limit",10);
//        $limit = $limit?intval($limit):10;
        $list = ShopUser::query()
            ->select(["id","name","address","longitude","latitude"])
//            ->addSelect(DB::raw($distance . ' as distances'))
            ->with(['workers'=>function($query){
                $query->where("status",0);
            }])
            ->withCount(["workers"=>function($query){
                $query->where("status",0);
            }])
//            ->having("distances","<=",$limit*1000)
            ->where("status",0)
            ->where("id",$shop_id)
            ->having("workers_count",">",0)
            ->orderByDesc("id")
            ->get();
        foreach ($list as $item){
//            $distances = $item->distances;
//            if ($distances>1000){
//                $item->distances = number_format($distances/1000,2)."km";
//            }else{
//                $item->distances = number_format($distances,2)."m";
//            }
            $item['workers'] = Helper::workers($item->workers);
        }
        return [
            'shops'=> $list
        ];
    }


    /**
     * @Apidoc\AddField("wait_money",type="float",default="0",desc="待结算金额")
     * @Apidoc\Returned(ref="App\Models\Worker")
     */
    public static function getDetail($user_id): Worker|null
    {
        $worker = self::whereUserId($user_id)->first();
        if ($worker){
            $worker->wait_money = OrderCommission::query()
                ->where("worker_id",$worker->id)
                ->where("is_settle",0)
                ->sum('worker_money');
            $cash_money = CashOrder::query()->where("type",1)
                ->where("worker_id",$worker->id)->where("status",0)->sum("amount");
            $worker->money = floatval($worker->money - $cash_money);
            $worker->money = number_format($worker->money,2);
        }
        return $worker;
    }


    /**
     * 员工师傅余额变更
     * @param int $type 类型 0=后台修改,1=订单金额,2=提现金额
     * @param int $worker_id 代理商ID
     * @param float $money 变更金额
     * @param string $remark 备注
     */
    public static function moneys(int $type, int $worker_id, float $money, string $remark){
        if ($money!=0){
            $worker = self::query()->where("id",$worker_id)->first();
            if ($worker){
                $pre_money = $worker->money;
                $after_money = $worker->money + $money;
                if ($type==2){
                    $used_money = $worker->used_money + abs($money);
                    $res = self::query()->where("id",$worker_id)->update(['money'=>$after_money,"used_money"=>$used_money]);
                }else{
                    $res = self::query()->where("id",$worker_id)->update(['money'=>$after_money]);
                }
                if ($res){
                    $data = [
                        'type'=>$type,
                        'user_id'=>$worker->user_id,
                        'worker_id'=>$worker_id,
                        'pre_money'=>$pre_money,
                        'money'=>$money,
                        'after_money'=>$after_money,
                        'remark'=>$remark
                    ];
                    WorkerMoney::create($data);
                }
            }
        }
    }

}
